package com.study.security.impl;

import com.alibaba.fastjson.JSONObject;
import com.study.common.constants.RedisCache;
import com.study.Util.IDUtil;
import com.study.modules.saas.repository.model.UserDO;
import com.study.modules.saas.service.UserService;
import com.study.security.domain.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    RedisCache redisCache;

    @Override
    public UserDetails loadUserByUsername(String uuid) throws UsernameNotFoundException {
        UserDO user = userService.getUserByUuid(uuid);
        String cacheCurrentUser = redisCache.getCurrentUser(uuid);
        if (StringUtils.isNotBlank(cacheCurrentUser)) {
            CurrentUser currentUser = JSONObject.parseObject(cacheCurrentUser, CurrentUser.class);
            String token = currentUser.getToken();
            log.info("将原有用户登出:{}", currentUser);
            redisCache.deletedUserToken(token);
            redisCache.deletedCurrentUser(uuid);
        }
        String token = IDUtil.randomUUID();
        CurrentUser currentUser = new CurrentUser(user, token);
        redisCache.setUserToken(token, uuid);
        redisCache.setCurrentUser(uuid, JSONObject.toJSONString(currentUser));
        return currentUser;
    }
}
